package cn.boat.router;

import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 消息队列与zookeeper交互的辅助类
 */
public class MetaZookeeper {

    public static Logger logger = LoggerFactory.getLogger(MetaZookeeper.class);

    private volatile ZkClient zkClient;
    public String metaRoot; // zk上SimpleMQ的根目录
    public String consumersPath; //zk上存放消费者的基本路径
    public String brokerIdsPath; //zk上存放brokerId的基本路径
    public String brokerTopicsPath;
    public String uniquePath; //zk上存储唯一值的路径
    public String configCenterPath; // zk上配置中心路径

    public MetaZookeeper(final ZkClient zkClient, final String root) {
        this.zkClient = zkClient;
        this.metaRoot = this.normalize(root);
        this.consumersPath = this.metaRoot + "/consumers";
        this.brokerIdsPath = this.metaRoot + "/brokers/ids";
        this.brokerTopicsPath = this.metaRoot + "/brokers/topics";
        this.uniquePath = this.metaRoot + "/uniqueId";
        this.configCenterPath = this.metaRoot + "/config";
    }

    private String normalize(final String root) {
        if (root.startsWith("/")) {
            return this.removeLastSlash(root);
        } else {
            return "/" + this.removeLastSlash(root);
        }
    }

    private String removeLastSlash(final String root) {
        if (root.endsWith("/")) {
            return root.substring(0, root.lastIndexOf("/"));
        } else {
            return root;
        }
    }
}
